package dao.impl;

import dao.IGoodDao;
import entity.Good;

public class GoodDaoImpl implements IGoodDao {
	Good[] good;

	public GoodDaoImpl() {
		good = new Good[20];
	}

	public GoodDaoImpl(int size) {
		good = new Good[size];
	}

	private int getUseIndex() {
		for (int i = 0; i < good.length; i++) {
			if (null == good[i]) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public boolean save(Good good) {
		int index = this.getUseIndex();
		if(-1 == index){
			return false;
		}
		for (int i = 0; i < index; i++) {
			if(this.good[i].getGoodId() == good.getGoodId()){
				return false;
			}
		}
		this.good[index] = good;
		return true;
	}

	@Override
	public boolean delete(Good good) {
		int index = this.getUseIndex();
		for (int i = 0; i < index; i++) {
			if (this.good[i].getGoodId() == good.getGoodId()) {
				for (int j = i; j < index; j++) {
					this.good[j] = this.good[j + 1];
				}
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean update(Good good) {
		int index = this.getUseIndex();
		for (int i = 0; i < index; i++) {
			if (this.good[i].getGoodId() == good.getGoodId()) {
				this.good[i] = good;
				return true;
			}
		}
		return false;
	}

	@Override
	public Good selectById(Good good) {
		int index = this.getUseIndex();
		for (int i = 0; i < index; i++) {
			if (good.getGoodId() == this.good[i].getGoodId()) {
				return this.good[i];
			}
		}
		return null;
	}

	@Override
	public Good[] selectAll() {
		return good;
	}

	@Override
	public Good selectByName(String name) {
		int index = this.getUseIndex();
		for (int i = 0; i < index; i++) {
			if (name.equals(good[i].getGoodName())) {
				return good[i];
			}
		}
		return null;
	}

	@Override
	public Good[] selectByPrice(double low, double high) {
		Good[] g = new Good[this.getUseIndex()];
		int index = this.getUseIndex();
		int count = 0;
		for (int i = 0; i < index; i++) {
			if (good[i].getGoodPrice() < high && good[i].getGoodPrice() > low) {
				g[count] = good[i];
				count++;

			}
		}
		return g;
	}

	@Override
	public Good[] selectByDown() {

		Good[] downg = new Good[getUseIndex()];
		int count = 0;
		for (Good g : good) {
			if (g == null){
				break;
			}
			if (!g.isGoodUp()  ) {
				downg[count] = g;
				count++;
			}
		}
		return downg;
	}

	@Override
	public Good[] selectByQuantity() {
		Good[] g = new Good[getUseIndex()];
		int count = 0;
		System.arraycopy(good, 0, g, 0, getUseIndex());
		for (int j = 0; j < getUseIndex() - 1; j++) {
			for (int i = 0; i < getUseIndex() - 1 - j; i++) {
				if (g[i].getGoodQuantity() < g[i + 1].getGoodQuantity()) {
					Good temp = g[i];
					g[i] = g[i + 1];
					g[i + 1] = temp;
				}
			}

		}
		return g;
	}
}